layui.use('form', function () {
    layui.form;
});
layui.use('element', function () {
    layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
});

var editIndex;
var layedit;
layui.use(['form', 'layedit', 'laydate'], function () {
    var form = layui.form,
        layer = layui.layer;
    layedit = layui.layedit;
    //设置上传图片接口
    layedit.set({
        uploadImage: {
            url: basePath + '/chat/upimg' //接口url
            , type: 'POST' //默认post
            , size: 1024 * 5
        }
    });
    //创建一个编辑器
    editIndex = layedit.build('LAY_demo_editor', {
        tool: ['face' //删除线
            , 'image'
            , 'strong' //加粗
            , 'italic' //斜体
            , 'underline' //下划线
            , '|' //分割线
            ,'left' //左对齐
            ,'center' //居中对齐
            ,'right' //右对齐
            , '|' //分割线
            ,'link' //超链接
        ],
        height: 120 //设置编辑器高度
    });

    form.verify({
        content: function () {
            layedit.sync(editIndex)
        }
    });
    form.render();
});
// document.onkeydown = function (event) {
//     var e = event || window.event;
//     if (e && e.keyCode == 13) { //回车键的键值为13
//         send();
//     }
// };

function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
/*控制鼠标移动到div显示或者隐藏div的滚动*/
function leftscroll(id) {
    if (id == 1) {
        document.getElementById("leftscroll").style.overflowY = "auto";
        document.getElementById("leftscroll").style.overflowX = "hidden";
    } else if (id == 2) {
        document.getElementById("leftscroll").style.overflowY = "hidden";
        document.getElementById("leftscroll").style.overflowX = "hidden";
    } else if (id == 3) {
        document.getElementById("msgcontent").style.overflowY = "auto";
        document.getElementById("msgcontent").style.overflowX = "hidden";
    } else if (id == 4) {
        document.getElementById("msgcontent").style.overflowY = "hidden";
        document.getElementById("msgcontent").style.overflowX = "hidden";
    }
}

var actuserid = null;
var app = new Vue({
    el: '#chat',
    data() {
        return {
            listnickname: [],
            listmessage: [],
            loginusername: userid
        }
    },
    mounted: function () {
        this.getlistnickname();
        window.alertnote = this.alertnote;
        window.activeuser = this.activeuser;
        window.appendmsg = this.appendmsg;
    },
    methods: {
        /**点击预览图片*/
        openimg: function (id) {
            var imgs = document.getElementById(id).getElementsByTagName("img");
            var pho="";
            for (var i=0;i<imgs.length;i++){
                var img = '<img src="'+$(imgs[i]).attr("src")+'" style="width:100%;">'
                layer.open({
                    type: 1,
                    title: '预览',
                    area: ['500px', '500px'],
                    shade: 0.6,//遮罩透明度
                    anim: 0,//0-6的动画形式，-1不开启
                    content: img
                });
            }
        },
        /*新信息提示*/
        alertnote: function (msgtouid) {
            var that = this;
            for (var i = 0; i < that.listnickname.length; i++) {
                console.log(that.listnickname[i].userid);
                if (that.listnickname[i].userid === msgtouid) {
                    layer.msg(that.listnickname[i].nickname + '发来一条信息', {
                        time: 1500,
                        icon: 0,
                        offset: '50px'
                    });
                }
            }
        },
        /*添加聊天记录*/
        appendmsg(mstype, revive, send, text) {
            var that = this;
            let date = new Date()
            text+=' '+dateFormat("HH:MI:SS", date);
            that.listmessage.push({msgtype: mstype, reciveuserid: revive, senduserid: send, sendtext: text});
            setTimeout(function () {
                document.getElementById("msg_end").scrollIntoView();
            }, 500)
        },
        /*设置点击左侧的列表的时候切换样式同时查找聊天记录*/
        selectStyle: function (item, acuserid) {
            this.$nextTick(function () {
                this.listnickname.forEach(function (item) {
                    Vue.set(item, 'active', false);
                });
                Vue.set(item, 'active', true);
            });
            this.getMessageList(acuserid);
            actuserid = acuserid;
        },
        /*获取左侧的聊天窗口*/
        getlistnickname: function () {
            var that = this;
            $.ajax({
                url: basePath + "/chat/lkfriends",
                data: "",
                contentType: "application/json;charset=UTF-8",
                type: "post",
                dataType: "json",
                success: function (data) {
                    that.listnickname = data;
                    document.getElementById('leftc').style.display = 'block';
                    document.getElementById('appLoading').style.display = 'none';
                },
                error: function (err) {
                    console.log("err:", err);
                }
            });
        },
        /*获取聊天记录*/
        getMessageList: function (username) {
            document.getElementById('waits').style.display = 'none';
            document.getElementById('words').style.display = 'none';
            document.getElementById('appLoading2').style.display = 'block';
            var that = this;
            $.ajax({
                type: 'post',
                url: basePath + '/chat/lkuschatmsg/' + username,
                dataType: 'json',
                contentType: "application/json;charset=UTF-8",
                success: function (msg) {
                    that.listmessage = msg;
                    document.getElementById('words').style.display = 'block';
                    document.getElementById('appLoading2').style.display = 'none';
                    document.getElementById("msg_end").scrollIntoView();
                    $('#msgcontent').ready(

                    );
                },
                error: function (err) {
                    console.log("err:", err);
                }
            })
        }
    }
})
//var randnumber=Math.ceil(Math.random()*1000)+1;
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
    //连接WebSocket节点
    websocket = new WebSocket("ws://localhost:8080//websocket/" + userid);
} else {
    alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
    //setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
    //setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
    setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
    //setMessageInnerHTML("close");
}
//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
    websocket.close();
};

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
    var msgs = innerHTML.split("|");
    if (msgs[0] === actuserid) {
        appendmsg("0", actuserid, msgs[0], msgs[1]);
    }else if(msgs[0] === "0"){
        layer.msg('当前用户不在线', {
            time: 1500,
            icon: 0,
            offset: '50px'
        });
    }else {
        alertnote(msgs[0])
    }
    document.getElementById("msg_end").scrollIntoView();
}

//关闭连接
function closeWebSocket() {
    websocket.close();
}
//发送消息
function send() {
    var layedit = layui.layedit;
    var message = layedit.getContent(editIndex);
    if (message.length == 0) {
        layer.msg("请输入发送的内容", {
            time: 2500,
            icon: 2,
            offset: "300px"
        });
        return;
    }
    // 将内容设置为空
    layedit.setContent(editIndex, "", false);

    websocket.send(actuserid + "|" + message);
    appendmsg("0", actuserid, userid, message);
    document.getElementById("msg_end").scrollIntoView();
}